<template>
  <div class="test">
    <template v-if="pageConfig && models">
      <template v-for="item in pageConfig">
        <div v-if="item.id === 'bpmdatatable'" class="bh-mb-16" :key="item.id">
          <Statistics v-if="models.statisticsMeta" :meta="models.statisticsMeta" :data="statisticsData" />
          <EmapTable
            v-if="datamodel"
            ref="listRef"
            :datamodel='datamodel'
            :queryPath="queryPath"
            :customColumns="customColumns"
            @check-change="controlButtom"
            @edit='edit'
            @del='del'
            @downloadComplete='onDataLoaded'
          />
        </div>
        <div v-if="item.id === 'bpmadvancedquery' && models.searchMeta" class="bh-mb-16" :key="item.id">
          <EmapSearchAdv
            :searchMeta="models.searchMeta"
            @search="onSearch"
          />
        </div>
        <ButtonArea
          v-if="item.id === 'bpmActionBtns' && models.toolbar"
          ref="buttonArea"
          :key="item.id"
          :toolbar="models.toolbar"
          :formUrl="formUrl"
          :table="$refs.listRef"
          :time="gridTime"
          :queryPath="queryPath"
          :tableRecord="tableRecord"
          :gridAlias="gridAlias"
          :tableManageNo="tableManageNo"
          :defKey="defKey"
          :taskid="taskid"
          @save-success="saveSuccess"
        />
      </template>
    </template>
    <bh-loading :model='loading.model' :open='loading.open'></bh-loading>
    <EmapPerson ref="person" @save-success="saveSuccess"></EmapPerson>
    <EmapJump ref="emapJump" @save-success="saveSuccess"></EmapJump>
    <SecondCheck ref="secondCheck" @on-confirm="confirmCheck"></SecondCheck>
  </div>
</template>

<script>
import { getMenuInfo, divideUrlAndQuery, flatternArr, normalizeMeta } from 'utils'
// import { BhButton } from 'bh-vue'
import { getSearchCondition } from 'utils/dataType'
import { request } from 'utils/http'
import Statistics from 'components/statistics'
import EmapTable from 'components/emap-table'
import EmapSearchAdv from 'components/emap-search-adv'
import ButtonArea from './ButtonArea'
import pageUtil from '../../lib/bh-vue/utils/pageUtil'
import { runTask } from './operation'
import { bhLoading } from 'bh-vue'
import EmapPerson from 'components/emap-person'
import EmapJump from 'components/emap-jump'

// import FormNextStep from 'components/form-next-step'
// import FormRender from 'components/form-render'
// import EmapFlowToolbar from 'components/emap-flow-toolbar'
import FormContent from 'components/form-content'
import FormFooter from 'components/form-footer'
import { fetchGrid  } from 'services/flow.service'
import SecondCheck from 'components/second-check'

export default {
  name: 'test',
  components:{
    EmapTable,
    EmapSearchAdv,
    Statistics,
    ButtonArea,
    bhLoading,
    EmapPerson,
    EmapJump,
    SecondCheck,
  },
  data () {
    return {
      models: null,
      statisticsData: null,
      datamodel: null,
      queryPath: '',
      customColumns: [],
      formUrl: '',
      gridTime: 0,
      tableRecord: null,
      gridAlias: null,
      tableManageNo: null,
      defKey: '',
      taskid: '',
      isSelf: true,
      submitURL: window.submitURL,
      appName: '',
      formContentRef: null,
      formFooterRef: null,
      loading: {
        model: '',
        open: false
      },
      personModal: false,
      allLoadTime: 50,
      timeStep: 100,
      pageLoadTime: 0,
    }
  },
  beforeRouteUpdate (to, from, next) {
    // ...
    pageUtil.hidePaper()
    next()
    this.init()
  },
  beforeRouteLeave (to, from, next) {
    pageUtil.hidePaper()
    next()
  },
  mounted() {
    this.init()
    this.initTableOptionclick()
  },
  computed: {
    pageConfig() {
      if (!this.models) {
        return null
      }
      const domList = $(this.models.runhtml)
      return domList.toArray().filter(item => item.nodeName === 'DIV').map(item => ({
        id: item.id,
        html: item.innerHTML
      }))
    },
    searchMap() {
      const { searchMeta } = this.models
      return (searchMeta || []).reduce((ret, item) => ({
        ...ret,
        [item.name]: item.dataType
      }), {})
    }
  },
  methods: {
    init() {
      const _this = this
      const menuName = this.$route.params.name
      if (!menuName) {
        return
      }

      const menuInfo = getMenuInfo(menuName)
      if (!menuInfo) {
        return
      }
      
      this.formUrl = menuInfo.url.replace('showGrid', 'showForm')

      fetchGrid(menuInfo.url, menuInfo.params).then(res => {
        const data = res.models
        if (data.gridMeta) {
          data.gridMeta = data.gridMeta.map(item => ({
            ...item,
            caption: item.caption || item.name
          }))
        }
        _this.gridAlias = res.models.gridAlias
        this.datamodel = data.gridMeta
        this.queryPath = divideUrlAndQuery(data.queryPath)
        this.appName = res.models.appName
        let showCheckBox = false
        res.models.toolbar.forEach(element=>{
          if(element.selectType > 0){
            showCheckBox = true
          }
        })
        const addedCols = []
        if(showCheckBox){
          addedCols.push({ colIndex: '0', type: 'checkbox'})
        }
        const controlsWidth = 43*(res.models.options.length)+ 16
        const optionsBtn = {
          colIndex: showCheckBox? '1': '0',
          type: 'tpl',
          width: controlsWidth,
          cellsAlign: 'center',
          align: 'center',
          column: {
              text: '操作',
              cellsRenderer: function(rowIndex, column, value, rowData) {  //row, column, value, rowData
                  const items = _this.models.options;
                  let html = '<div style="text-align:center;">';
                  $.each(items, (i, item) => {
                    html += _this.getOptItem(rowData, item, (items.length-1)!==i, rowIndex, column, value);
                  });
                  html +="</div>"
                  return html;
              }
          }
        }
        addedCols.push(optionsBtn)
        this.customColumns = addedCols
        //快速搜索字段字典增加参数
        data.searchMeta.forEach(element => {
          if(element.url) {
            element.defaultBuilder = element.defaultBuilder || element.builder
            element.caption = element.caption || element.name
            const dicId = element.url ? element.url.match(/\/dic\/(\S*).do/)[1] : ''
            const thirdParams = element.url ? "sign=" + data.supportSigns[dicId] + "&time=" + data.time : ''
            if (thirdParams && element.url.indexOf(thirdParams) === -1) {
              element.url = element.url + "?" + thirdParams
            }
          }
        })
        this.models = data
        this.pageConfig.forEach(element => {
          if(element.id === "bpmadvancedtitle"){
            $("article .bh-paper-pile-dialog-headerTitle").html(element.html)
          }
        })
      })
    },
    getOptItem (rowData, item, notLast, rowIndex) {
        rowData = JSON.stringify(rowData)
        let disabled = ''
        item.manage = item.manage || 0
        rowData = this.gridDatas.result.rows[rowIndex]
        if(rowData && (rowData['$$manage'] <= item.manage)){
          disabled = "disabled"
        }
        // if(rowData.verify && rowData.verify.___taskStatus === 1){
        //   disabled = "disabled"
        // }
        if(!this.judgeVerify(rowData, item)) {
          disabled = "disabled"
        }

        let itemData = JSON.stringify(item)
        if (item.type === 'button') {
            return "<button data-name='" + item.name + "' data-row='" + rowData + "' class='opt-button'> style='padding: 0 5px;'" + item.title + '</button>'
        } else {
            return "<a href='javascript:void(0)' data-item='" + itemData + "' " + disabled + " data-index='" + rowIndex +  "' data-row='" + rowData + "' class='opt-button' style='padding: 0 5px;'>" + item.title + '</a>'+ (notLast? '|':'')
        }
    },
    //权限判断
    judgeVerify(row, item){
      let verify = item.verify
      for (let key in verify) {
        var checkArr = verify[key];
        var tmpResult = false;
        for (let i = 0; i < checkArr.length; i++) {
          if (checkArr[i] === row[key]) {
            tmpResult = true;
            break;
          }
        }
        if (!tmpResult) {
          return false;
        }
      }
      return true;
    },
    initTableOptionclick() {
      const vm = this
      function run(e) {
        runTask(vm, null, e)
      }
      $(this.$el).off('click', '.opt-button', run).on('click', '.opt-button', run);
    },
    // flowHandle(formItem, rowIndex){
    //   const vm = this
    //   const recordData = this.gridDatas.result.rows[rowIndex]
    //   pageUtil.confirm("确认"+ formItem.title +"当前流程？",function(){
    //     const url = "/sys/emapflow"+ formItem.path
    //     let isDelete = false
    //     formItem.params.forEach(element=>{
    //       if(element.name === "isDelete"){
    //         isDelete = element.value
    //       }
    //     })
    //     const params = {
    //       appName: vm.appName.name,
    //       processInstanceId: recordData.___procId,
    //       isDelete: isDelete
    //     }
    //     request(url, {
    //       query: {
    //         ...params
    //       },
    //     }).then(res => {
    //       if(res.succeed){
    //         pageUtil.tip("操作成功","success")
    //         vm.$refs.listRef[0].reload();
    //       }else{
    //         pageUtil.tip("操作失败","danger")
    //       }
    //     }).catch(e=>{
    //       pageUtil.tip(e, "danger")
    //     })
    //   })
    // },
    // //单行删除表格数据
    // deleteRows(rowIndex){
    //   const recordData = this.gridDatas.result.rows[rowIndex]
    //   const vm = this
    //   pageUtil.confirm("确认删除？",function(){
    //     const deleteUrl = vm.formUrl.replace("showForm.do", "deleteData.do")
    //     const deleteDatas = {"time":vm.gridTime, rows: []}
    //     const obj = {
    //       bizKey: recordData['$$bizKey'],
    //       sign: recordData['$$sign']
    //     }
    //     deleteDatas.rows.push(obj)
    //     request(deleteUrl, {
    //       query: {
    //         alias: vm.queryPath.params.alias,
    //         keys: JSON.stringify(deleteDatas),
    //       },
    //     }).then(res => {
    //       if(res.code === "0"){
    //         pageUtil.tip("删除成功","success")
    //         vm.$refs.listRef[0].reload();
    //       }else{
    //         pageUtil.tip("删除失败","danger")
    //       }
    //     }).catch(e=>{
    //       pageUtil.tip(e, "danger")
    //     })
    //   })
    // },
    // tableOption(item){
    //   console.log(item, 'item')
    // },
    // 表格数据加载事件
    onDataLoaded(event) {
      this.gridDatas = event.datas
      this.gridTime = this.gridDatas && this.gridDatas.time
      this.statisticsData = this.gridDatas && this.gridDatas.statistics
    },
    getSearchBuilder(name) {
      if (this.searchMap[name]) {
        return getSearchCondition(this.searchMap[name])
      } else {
        return 'include'
      }
    },
    // 搜索触发
    onSearch(e) {
      const jsonObj = JSON.parse(e)
      let searchParamsArr = flatternArr(jsonObj)
      searchParamsArr = searchParamsArr.reduce((setting, element) => {
        var dateQuerySetting = [];
        if (this.searchMap[element.name] === 'String') {
          var settingItem = {}
          if (Array.isArray(element.value)) {
            settingItem = {
              "name": element.name,
              "linkOpt": element.linkOpt || "AND",
              "builder": "m_value_equal",
              "value": element.value.join(',')
            };
          } else {
            settingItem = {
              "name": element.name,
              "linkOpt": element.linkOpt || "AND",
              "builder": element.builder || 'include',
              "value": element.value
            };
          }
          setting.push(settingItem);
        } else if (this.searchMap[element.name] === 'Timestamp' && element.value && Array.isArray(element.value) && element.value[0] != '') {
          dateQuerySetting = [];
          dateQuerySetting[0] = {
            "name": element.name,
            "linkOpt":  element.linkOpt || "AND",
            "builder": "moreEqual",
            "value": element.value[0]
          };
          dateQuerySetting[1] = {
            "name": element.name,
            "linkOpt": element.linkOpt || "AND",
            "builder": "lessEqual",
            "value": element.value[1]
          };
          setting.push(dateQuerySetting);
        } else if ((this.searchMap[element.name] === 'int' || this.searchMap[element.name] === 'double' || this.searchMap[element.name] === 'long') && element.value && Array.isArray(element.value) && element.value[0] != '' && element.value[1] != '') {
          dateQuerySetting = [];
          dateQuerySetting[0] = {
            "name": element.name,
            "linkOpt": element.linkOpt || "AND",
            "builder": "moreEqual",
            "value": element.value[0]
          };
          dateQuerySetting[1] = {
            "name": element.name,
            "linkOpt": element.linkOpt || "AND",
            "builder": "lessEqual",
            "value": element.value[1]
          };
          setting.push(dateQuerySetting);
        }else{
          if(!element.builder){
            element.builder = this.getSearchBuilder(element.name)
          }
          setting.push(element)
        }
        // 时间范围特殊处理
        // if (this.searchMap[element.name] === 'Timestamp') {
        //   const [start, end] = element.value.split(',')
        //   ret.push([
        //     { ...element, value: start, builder: 'moreEqual'},
        //     { ...element, value: end, builder: 'lessEqual'},
        //   ])
        // } else {
        //   element.builder = this.getSearchBuilder(element.name)
        //   ret.push(element)
        // }
        return setting
      }, [])

      this.$refs.listRef[0].reload({
        querySetting: searchParamsArr.length > 0 ? JSON.stringify(searchParamsArr) : undefined
      })
    },
    edit: function(row) {
        console.log('edit', row);
    },
    del: function(row) {
        console.log('del', row);
        // refresh after delete
        this.options.params = {keyword: 'inputVal'}; // 设置查询参数
        this.$refs.listRef[0].reload();
    },
    submitFn(val){
      console.log(val,"submitVal")
    },
    controlButtom(vmArr){
      const _this = this
      vmArr.forEach(element => {
        _this.tableManageNo = element['$$manage']
      });
      this.tableRecord = vmArr.length
    },
    saveSuccess(item) {
      // console.log(res, 'saveSuccess')
      // if (item.refresh) {
      //   this.$refs.listRef[0].reload();
      // }
      console.log(item)
      this.$refs.listRef[0].reload();
    },
    confirmCheck(value, checkOptions) {
      const verifyCode = value.verifyCode
      checkOptions.options.queryParams['verifyCode'] = value.verifyCode
      this.renderConnmon(checkOptions.vm, checkOptions.item, checkOptions.key, checkOptions.options)
    },
    secondCheck(vm, item, key, options) {
      const _this = this
      this.$refs.secondCheck.checkModal = true
      this.$refs.secondCheck.formUrl = vm.formUrl
      this.$refs.secondCheck.checkOptions['vm'] = vm
      this.$refs.secondCheck.checkOptions['item'] = item
      this.$refs.secondCheck.checkOptions['key'] = key
      this.$refs.secondCheck.checkOptions['options'] = options
    },
    renderConnmon(vm, item, key, options) {
        const _this = this
        const { queryParams } = options || {}
        const queryData = {
          alias: item.form,
          key: key,
          gridAlias: vm.gridAlias,
          readonly: item.formReadOnly ? "1": undefined,
          ...(queryParams || {})
        }

        // if (item.params) {
        //   item.params.forEach(param => {
        //     queryData[param.name] = param.value
        //   })
        // }

        request(vm.formUrl, {
          query: queryData,
        }).then(res => {
          if(res && res.code === "0") {
            //二次验证
            if(res.datas && res.datas.result === undefined){
              _this.secondCheck(vm, item, key, options)
              return
            }

            let runjs = JSON.parse(res.models.runjs)
            res.models.runjs = runjs
            res.models.gridAlias = vm.gridAlias
            let formDefKey = res.datas.defKey
            let formTaskId = res.datas.taskId || ''
            const formReadOnly = res.models.formReadOnly

            res.models.meta && res.models.meta.forEach(item => {   // 后端保存时间有问题，此处需要处理
              normalizeMeta(item)  //类型处理
            })

            const flowConfig = res.datas && res.datas.flowConfig || {}
            const instanceId =  flowConfig.processInstanceId
            const needFlowOpt = res.datas && res.datas.needFlowOpt

            if (needFlowOpt) {
              if (flowConfig.needSelectAssignees && !formReadOnly) {
                let nextNode = {"type":"flow-next-step","name":"下一步处理人","icon":"icon-subtitles","options":{},"key":"emap-flow-next-step_1576726377000_87961"}
                runjs.children.push(nextNode)
              }
            } else { // needFlowOpt 不为 true 时，不需要展示下列控件
              const controls = runjs.children
              for (let i = controls.length - 1; i >= 0; i--) {
                if (['audit-comment'].includes(controls[i].type)) {
                  controls.splice(i, 1)
                }
              }
            }

            const flowInfo = {
              processInstanceId: instanceId || '',
              taskId: formTaskId,
              defKey: formDefKey,
              appName: formDefKey && formDefKey.split('.')[0],
              language: 'zh',
            }

            const content = `
              <FormContent
                ref="formContextParent"
                :flowOpts="flowOpts"
                :formOpts="formOpts"
                :otherOpts="otherOpts"
                :itemData="itemData"
                :formUrl="formUrl"
                :flowInfo="flowInfo"
                :options="options"
                :formContentRef="formContentRef"
                :formFooterRef="formFooterRef"
                @on-change="formChange"
                @save-success="saveSuccess"
              />
            `
            let footerContent = `
              <FormFooter
                ref="formFooterParent"
                :flowOpts="flowOpts"
                :formOpts="formOpts"
                :otherOpts="otherOpts"
                :itemData="itemData"
                :formUrl="formUrl"
                :options="options"
                :processedFormData="processedFormData"
                :flowComment="flowComment"
                :formContentRef="formContentRef"
                :formFooterRef="formFooterRef"
                @save-success="saveSuccess"
              >
              </FormFooter>
            `
            pageUtil.showVuePaper(vm, item.title, content, footerContent, null, function onClose() {
              if (vm.formContentRef) {
                vm.formContentRef.$destroy()
              }
              if (vm.formFooterRef) {
                vm.formFooterRef.$destroy()
              }
            }, {
                data () {
                    return {
                      flowOpts: res.datas,
                      formOpts: res.models,
                      otherOpts: {},
                      itemData: item,
                      options: { ...(options || {}), readonly: formReadOnly},
                      flowInfo: flowInfo,
                      formUrl: vm.formUrl,
                      formDataChange: {},
                      flowComment: {},
                      processedFormData: {},
                      formContentRef: vm.formContentRef,
                      formFooterRef: vm.formFooterRef,
                    }
                },
                methods:{
                  formChange(){
                    // this.formDataChange = value
                    // if (vm.formFooterRef) {
                    //   vm.formFooterRef.setProcess(value)
                    //   const flowCommentParams={
                    //     approval: value.approval,
                    //     flowComment: value.flowComment,
                    //     elecsealUrl: value.elecsealUrl
                    //   }
                    //   vm.formFooterRef.setComment(flowCommentParams)
                    // }
                  },
                  onReady(e, blockName) {
                    if(blockName === 'content' && e.$refs.formContextParent && e.$refs.formContextParent.$refs.form) {
                      vm.formContentRef = e.$refs.formContextParent
                    }
                    // if(blockName === 'footer' && e.$refs.formFooterParent && e.$refs.formFooterParent.$refs.toolbar) {
                    //   vm.formFooterRef = e.$refs.formFooterParent
                    //   vm.formFooterRef.setProcess(res.datas.result)
                    // }
                    if(e.$refs.formContextParent && e.$refs.formContextParent.$refs.form){
                      e.$refs.formContextParent.$refs.form.setValue(res.datas.result)
                    }
                    if(vm.formContentRef && vm.formFooterRef){
                      vm.formFooterRef.initFile()
                    }
                  },
                  closeForm() {
                    pageUtil.hidePaper()
                  },
                  saveSuccess(item){
                    _this.saveSuccess(item)
                  }
            },
            mounted() {

            },
            components: {
                /* eslint-disable-next-line */
                FormContent,
                /* eslint-disable-next-line */
                FormFooter,
            },
            beforeDestroy() {
              $(this.$el).off('click', '.opt-button')
              pageUtil.hidePaper()
            },
            })
          }else{
            this.tip("请求失败","danger")
          }
        })
    }
  }
}
</script>

<style scoped>

</style>
